import { getToken, removeToken, setToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { getInfo, login, logout } from '@/api/system/user'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  userId: '',
  roles: [],
  permissions: [], // 用户权限
  wxServerUrl: ''// 微信地址
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_SHOW_NAME: (state, showName) => {
    state.showName = showName
  },
  SET_PASSWORD: (state, password) => {
    state.password = password
  },
  SET_USERID: (state, id) => {
    state.userId = id
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_WX_SERVER_URL: (state, url) => {
    state.wxServerUrl = url
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, rememberMe } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName: username.trim(), password: password, rememberMe: rememberMe }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        data.avatar = data.avatar || 'https://ui-avatars.com/api/?background=1890ff&color=fff&name=' + data.loginName
        const { roles, showName, avatar, password, permissions, id } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('账号未分配权限，无法登入!')
        }
        commit('SET_ROLES', roles)
        commit('SET_SHOW_NAME', showName)
        commit('SET_PASSWORD', password)
        commit('SET_AVATAR', avatar)
        commit('SET_USERID', id)
        commit('SET_PERMISSIONS', permissions)
        commit('SET_WX_SERVER_URL', 'http://weixin-dev6.szsanshan.com')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_PASSWORD', '')
        commit('SET_WX_SERVER_URL', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { permissions } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', permissions, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
